import { createStore } from "vuex";
import { INCREMENT_N } from "./mutation-types";
import axios from "axios";
const store = createStore({
  state() {
    return {
      counter: 100,
      username: "",
      address: null,
      testVuexValue: null,

      name: "pengfan",
      age: 18,
      height: 1.88,
      books: [
        { name: "vue从入门到全能秀", price: 100, count: 3 },
        { name: "node从入门到崩溃", price: 200, count: 2 },
        { name: "webpack从入门到入土", price: 120, count: 1 },
        { name: "react从入门到放弃", price: 150, count: 5 },
      ],
      discount: 0.6,
      banners: [],
    };
  },
  mutations: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    setUsername(state, payload) {
      state.username = payload;
    },
    setAddress(state, payload) {
      state.address = payload;
    },
    setTestVuexValue(state, payload) {
      state.testVuexValue = payload;
    },
    [INCREMENT_N](state, payload) {
      state.counter += payload.counter;
    },
    addBanners(state, payload) {
      state.banners = payload;
    },
  },
  getters: {
    totalPrice(state, getters) {
      let totalPrice = 0;
      for (let book of state.books) {
        totalPrice += book.count * book.price;
      }
      return (totalPrice * getters.currentDiscount).toFixed(2);
    },

    currentDiscount(state) {
      return state.discount * 0.9;
    },

    totalPriceCountGreaterN(state, getters) {
      return function(n) {
        let totalPrice = 0;
        for (let book of state.books) {
          if (book.count > n) {
            totalPrice += book.count * book.price;
          }
        }
        return totalPrice * getters.currentDiscount;
      };
    },

    nameInfo(state) {
      return `name: ${state.name}`;
    },
    ageInfo(state) {
      return `name: ${state.age}`;
    },
    heightInfo(state) {
      return `name: ${state.height}`;
    },
  },
  actions: {
    incrementAction(context) {
      setTimeout(() => {
        context.commit("increment");
      }, 1000);
    },

    // 2.context的其他属性
    decrementAction(
      { commit, dispatch, state, rootState, getters, rootGetters },
      payload
    ) {
      commit("decrement");
      console.log(payload);
    },
    getHomeMultidata(context) {
      return new Promise((resolve, reject) => {
        axios
          .get("http://123.207.32.32:8000/home/multidata")
          .then(({ data }) => {
            context.commit("addBanners", data.data.banner.list);
            resolve({ name: "pengfan", age: 18 });
          });
      }).catch((err) => {
        reject(err);
      });
    },
  },
});

export default store;
